import { makeAutoObservable, runInAction } from 'mobx';
import { RootStore } from './index';
// import { apiRequest } from '../utils/apiRequest';

export interface Expense {
  id: string;
  title: string;
  amount: number;
  category: string;
  date: string;
  description?: string;
  createdAt: string;
  updatedAt: string;
}

export interface CreateExpenseData {
  title: string;
  amount: number;
  category: string;
  date: string;
  description?: string;
}

export class ExpenseStore {
  rootStore: RootStore;
  expenses: Expense[] = [];
  isLoading = false;
  error: string | null = null;

  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this);
  }

  setExpenses(expenses: Expense[]) {
    this.expenses = expenses;
  }

  addExpense(expense: Expense) {
    this.expenses.unshift(expense);
  }

  updateExpenseInList(expense: Expense) {
    const index = this.expenses.findIndex(e => e.id === expense.id);
    if (index !== -1) {
      this.expenses[index] = expense;
    }
  }

  removeExpense(id: string) {
    this.expenses = this.expenses.filter(e => e.id !== id);
  }

  setLoading(loading: boolean) {
    this.isLoading = loading;
  }

  setError(error: string | null) {
    this.error = error;
  }

  async fetchExpenses() {
    this.setLoading(true);
    this.setError(null);

    // try {
    //   const response = await apiRequest('/expenses');
    //   if (response.success) {
    //     runInAction(() => {
    //       this.setExpenses(response.data.expenses);
    //     });
    //   } else {
    //     runInAction(() => {
    //       this.setError(response.message || '获取费用列表失败');
    //     });
    //   }
    // } catch (error) {
    //   runInAction(() => {
    //     this.setError('网络错误，请稍后重试');
    //   });
    // } finally {
    //   this.setLoading(false);
    // }
  }

  async createExpense(data: CreateExpenseData) {
    this.setLoading(true);
    this.setError(null);

    // try {
    //   const response = await apiRequest('/expenses', {
    //     method: 'POST',
    //     body: JSON.stringify(data),
    //   });

    //   if (response.success) {
    //     runInAction(() => {
    //       this.addExpense(response.data.expense);
    //     });
    //     return { success: true };
    //   } else {
    //     runInAction(() => {
    //       this.setError(response.message || '创建费用失败');
    //     });
    //     return { success: false, message: response.message };
    //   }
    // } catch (error) {
    //   runInAction(() => {
    //     this.setError('网络错误，请稍后重试');
    //   });
    //   return { success: false, message: '网络错误' };
    // } finally {
    //   this.setLoading(false);
    // }
  }

  async updateExpense(id: string, data: Partial<CreateExpenseData>) {
    this.setLoading(true);
    this.setError(null);

    // try {
    //   const response = await apiRequest(`/expenses/${id}`, {
    //     method: 'PUT',
    //     body: JSON.stringify(data),
    //   });

    //   if (response.success) {
    //     runInAction(() => {
    //       this.updateExpenseInList(response.data.expense);
    //     });
    //     return { success: true };
    //   } else {
    //     runInAction(() => {
    //       this.setError(response.message || '更新费用失败');
    //     });
    //     return { success: false, message: response.message };
    //   }
    // } catch (error) {
    //   runInAction(() => {
    //     this.setError('网络错误，请稍后重试');
    //   });
    //   return { success: false, message: '网络错误' };
    // } finally {
    //   this.setLoading(false);
    // }
  }

  async deleteExpense(id: string) {
    this.setLoading(true);
    this.setError(null);

    // try {
    //   const response = await apiRequest(`/expenses/${id}`, {
    //     method: 'DELETE',
    //   });

    //   if (response.success) {
    //     runInAction(() => {
    //       this.removeExpense(id);
    //     });
    //     return { success: true };
    //   } else {
    //     runInAction(() => {
    //       this.setError(response.message || '删除费用失败');
    //     });
    //     return { success: false, message: response.message };
    //   }
    // } catch (error) {
    //   runInAction(() => {
    //     this.setError('网络错误，请稍后重试');
    //   });
    //   return { success: false, message: '网络错误' };
    // } finally {
    //   this.setLoading(false);
    // }
  }

  get totalAmount() {
    return this.expenses.reduce((sum, expense) => sum + expense.amount, 0);
  }

  get expensesByCategory() {
    const grouped = this.expenses.reduce(
      (acc, expense) => {
        if (!acc[expense.category]) {
          acc[expense.category] = [];
        }
        acc[expense.category].push(expense);
        return acc;
      },
      {} as Record<string, Expense[]>
    );

    return Object.entries(grouped).map(([category, expenses]) => ({
      category,
      expenses,
      total: expenses.reduce((sum, expense) => sum + expense.amount, 0),
    }));
  }
}
